<?php
require_once(APPPATH . 'controllers/frontend/layout.php');

class Contact extends Layout {
    
    
    private $_capt = "public/template/backend/images/captcha/";
    public $_format = "Y-m-d H:i:s";
    
    public function __construct() {
        parent::__construct();
        $this->load->helper('captcha');
    }
    
    public function index(){
        $val = array(
            "word"      =>  "",
            "img_path" => $this->_capt, //đường dẫn để tạo img captcha.
            "img_url" => base_url($this->_capt).'/', //đã là đường dẫn để hiển thị hình ảnh sau khi tạo xong captcha
            'img_width'	=> 150,
            'img_height' => 30
        );
        $cap = create_captcha($val);
        $data = array(
            'captcha_time' => $cap['time'],
            'ip_address' => $this->input->ip_address(),
            'word' => $cap['word']
        );

        $query = $this->db->insert_string('captcha', $data);
        $this->db->query($query);
        $this->_data['data']['capt'] = $cap['image'];
        
        $expiration = time() - 600; // clear table
        $this->db->delete('captcha', array('captcha_time <' => $expiration));

        if ($this->input->post("contact")) {
            $post = $this->input->post("data");
                                           
            $this->form_validation->set_error_delimiters('<label class="error">', '</label>');
            $this->form_validation->set_rules('data[email]', 'Email', 'trim|required|valid_email|xss_clean');
            $this->form_validation->set_rules('data[name]', 'Tên', 'trim|required');
            $this->form_validation->set_rules('captcha', 'Mã an toàn', 'trim|required');
            $this->form_validation->set_rules('data[title]', 'Tiêu đề', 'trim|required');
            $this->form_validation->set_rules('data[content]', 'Nội dung', 'trim|required');
            if ($this->form_validation->run() == TRUE) {

                // Then see if a captcha exists:
                $sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
                $binds = array($_POST['captcha'], $this->input->ip_address(), $expiration);
                $query = $this->db->query($sql, $binds);
                $row = $query->row();
                
                if ($row->count == 0) {
                    $this->_data['data']['notice'] = "Mã an toàn sai";
                } else {
                    $post['posted'] = gmdate($this->_format, time() + 7 * 3600);
                    $this->mcontacts->insert($post);
                    $this->_data['data']['notice'] = "Gửi thành công";
                }              
            }
        }
        $this->_data['title'] = "Liên hệ";
        $this->_data['temp'] = "frontend/contact/index";
        $this->load->view('frontend/layout/index',$this->_data);
    }

}
